package com.hwhhhh.mygrad;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.reflect.TypeToken;
import com.hwhhhh.mygrad.api.Api;
import com.hwhhhh.mygrad.api.ApiCallback;
import com.hwhhhh.mygrad.api.ApiConfig;
import com.hwhhhh.mygrad.entity.RespData;
import com.hwhhhh.mygrad.dto.UserDTO;
import com.hwhhhh.mygrad.utils.StringUtils;

import java.util.HashMap;

public class RegisterActivity extends BaseActivity {
    private EditText etEmail;
    private EditText etPwd;
    private Button btnRegister;

    @Override
    protected void initView() {
        etEmail = findViewById(R.id.et_register_email);
        etPwd = findViewById(R.id.et_register_pwd);
        btnRegister = findViewById(R.id.btn_register);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void initData() {
        setBarColor(R.color.background_color);
        btnRegister.setOnClickListener(v -> {
            String account = etEmail.getText().toString().trim();
            String pwd = etPwd.getText().toString().trim();
            register(account, pwd);
        });
    }

    private void register(String account, String pwd) {
        if (StringUtils.isEmpty(account)) {
            showToast("请输入注册账号！");
            return;
        }
        if (StringUtils.isEmpty(pwd)) {
            showToast("请输入注册密码！");
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("email", account);
        params.put("password", pwd);
        Api.config(ApiConfig.REGISTER, params).postRequest(this, new ApiCallback() {
            @Override
            public void onSuccess(String res) {
                RespData<UserDTO> respData = StringUtils.fromJson(res, new TypeToken<RespData<UserDTO>>(){}.getType());
                if (respData.getCode() == 200) {
                    UserDTO entity = respData.getData();
                    String token = entity.getToken();
                    saveStringToSp("token", token);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", entity);
                    navigateToWithFlag(HomeActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    showToastSync("注册成功,用户id：" + entity.getId());
                } else {
                    showToastSync("邮箱已存在，请重新注册！");
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("网络异常，请重新注册！");
            }
        });
    }
}